package com.yfp.auth.controller;

import com.yfp.auth.domain.UpdatePwdDTO;
import com.yfp.auth.form.CaptchaBody;
import com.yfp.auth.form.LoginBody;
import com.yfp.auth.form.ResetPasswordBody;
import com.yfp.auth.form.UserVO;
import com.yfp.auth.service.SysLoginService;
import com.yfp.auth.valid.LoginValidGroup;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.JwtUtils;
import com.yfp.common.core.utils.StringUtils;
import com.yfp.common.core.utils.sign.RsaUtils;
import com.yfp.common.core.web.domain.AjaxResult;
import com.yfp.common.security.auth.AuthUtil;
import com.yfp.common.security.service.TokenService;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.system.api.model.LoginUser;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * token 控制
 *
 *
 */
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) throws Exception {
        // 用户登录
        String password = RsaUtils.decryptByPrivateKey(form.getPassword());
        LoginUser userInfo = sysLoginService.login(form.getUsername(), password);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @Operation(summary = "获取短信验证码")
    @PostMapping("captcha")
    public R<?> captcha(@Validated(value = LoginValidGroup.Captcha.class) @RequestBody CaptchaBody captchaBody) {
        return R.ok(sysLoginService.getCaptcha(captchaBody));
    }

    @Operation(summary = "登录接口", description = "短信验证码登录接口")
    @PostMapping("login/captcha")
    public R<?> loginCaptcha(@Validated(value = LoginValidGroup.CaptchaLogin.class) @RequestBody LoginBody loginBody) {
        // 用户登录
        LoginUser userInfo = sysLoginService.loginCaptcha(loginBody);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @Operation(summary = "登录接口", description = "账号密码登录接口")
    @PostMapping("login/password")
    public R<?> loginPassword(@Validated(value = LoginValidGroup.PasswordLogin.class) @RequestBody LoginBody loginBody) throws Exception {
        // 用户登录
        String password = RsaUtils.decryptByPrivateKey(loginBody.getPassword());
        LoginUser userInfo = sysLoginService.loginPassword(loginBody.getPhone(), password);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @Operation(summary = "重置密码接口", description = "重置密码")
    @PostMapping("reset/password")
    public R<?> resetPassword(@Validated(value = LoginValidGroup.ResetPassword.class) @RequestBody ResetPasswordBody resetPasswordBody) throws Exception {
        resetPasswordBody.setNewPassword(RsaUtils.decryptByPrivateKey(resetPasswordBody.getNewPassword()));
        resetPasswordBody.setRepeatNewPassword(RsaUtils.decryptByPrivateKey(resetPasswordBody.getRepeatNewPassword()));
        sysLoginService.resetPassword(resetPasswordBody);
        return R.ok();
    }


    /**
     * 修改密码
     */
    @Operation(summary = "修改密码")
    @PostMapping("/updatePwd")
    public R<?> updatePwd(@RequestBody UpdatePwdDTO updatePwdDTO) throws Exception {
        sysLoginService.updatePwd(updatePwdDTO.getOldPassword(),updatePwdDTO.getNewPassword());
        return R.ok();
    }



    @Operation(summary = "浏览器标识", description = "用于判断是否是首次登录，首次使用此浏览器")
    @GetMapping("login/method")
    public R<?> resetPassword(@ApiParam(value = "浏览器标识") String token) {
        return R.ok(sysLoginService.isFirstBrowserLogin(token));
    }

    @Operation(summary = "获取用户信息", description = "获取用户信息")
    @GetMapping("user")
    public R<UserVO> getUserInfo() {
        return R.ok(sysLoginService.getUserInfo());
    }
}
